<script>

import { copy, handleTree, isNull } from "@/utils/service";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { add, remove, update } from "@/views/superAdmin/menu/api";
import { hasPermission } from "@/utils/auth";

export default {
  name: "menuV2",
  components: { Treeselect },
  data() {
    return {
      query: {
        menuName: ""
      },
      /** 数据*/
      tree: [],
      /** 提供选项*/
      menuTree: [],
      /** 对话窗相关参数*/
      dialog: {
        visible: false,
        title: "添加菜单",
        params: {
          id: undefined,
          // 菜单名称
          name: "",
          //权限标识
          permissions: "",
          //访问路径
          requestUrl: "",
          // 组件路径
          component: "",
          // 菜单图标
          menuIcon: "",
          parentId: -1,
          keepAlive: false,
          //排序编号
          sort: 1,
          // 类型 1菜单权限 2操作权限
          flag: 1
        },
        rules: {
          name: [
            { required: true, message: "请输入菜单名称", trigger: "blur" }
          ],
          flag: [
            { type: "enum", enum: [1, 2], trigger: "blur", message: "不支持的类型" }
          ],
          requestUrl: [
            {
              validator: function(_rule, value, callback) {
                if (this.dialog.params.flag === 1 && this.dialog.params.parentId !== -1) {
                  if (isNull(value)) {
                    callback(new Error("请填写访问路径"));
                  }
                }
                callback();
              }.bind(this), trigger: "blur"
            }
          ],
          component: [
            {
              validator: function(_rule, value, callback) {
                if (this.dialog.params.flag === 1 && this.dialog.params.parentId !== -1) {
                  if (isNull(value)) {
                    callback(new Error("请填写组件路径"));
                  }
                }
                callback();
              }.bind(this), trigger: "blur"
            }
          ],
          permissions: [
            {
              validator: function(_rule, value, callback) {
                if (this.dialog.params.flag === 2) {
                  if (isNull(value)) {
                    callback(new Error("请填写权限代码"));
                  }
                }
                callback();
              }.bind(this), trigger: "blur"
            }
          ]
        }
      }

    };
  },
  created() {
    this.getTree();
  },
  methods: {
    getTree() {
      if (!hasPermission("menu.query")) {
        this.$message.warning("您无权限访问此页面列表");
        return;
      }
      let _ = this;
      this.$request.post({
        url: "superAdmin/adMenu/list",
        params: _.query,
        success: res => {
          _.tree = handleTree(res, "id", "parentId", "children", -1);
          _.menuTree = copy(_.tree);
          _.menuTree.unshift({ id: -1, sort: 0, menuName: "根目录" });
        }
      });
    },
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.getTree();
    },
    /** 新增按钮操作*/
    handleAdd(row) {
      if (row) {
        this.dialog.params.parentId = row.id;
      } else {
        this.dialog.params.parentId = -1;
      }
      this.dialog.params.name = "";
      this.dialog.params.sort = 0;
      this.dialog.params.id = undefined;
      this.dialog.params.permissions = "";
      this.dialog.params.requestUrl = "";
      this.dialog.params.component = "";
      this.dialog.params.menuIcon = "";
      this.dialog.title = "添加菜单";
      this.dialog.params.flag = 1;
      this.dialog.params.keepAlive = false;
      this.dialog.visible = true;
    },
    /** 修改按钮操作*/
    handleUpdate(row) {
      this.dialog.title = "修改菜单";
      this.dialog.params.id = row.id;
      this.dialog.params.parentId = row.parentId;
      this.dialog.params.name = row.menuName;
      this.dialog.params.flag = row.flag;
      this.dialog.params.permissions = row.permissions;
      this.dialog.params.requestUrl = row.requestUrl;
      this.dialog.params.component = row.component;
      this.dialog.params.sort = row.sort;
      this.dialog.params.keepAlive = row.keepAlive;
      this.dialog.visible = true;
    },
    /** 删除按钮操作*/
    handleDelete(id) {
      const loading = this.$loading({
        lock: true,
        text: "提交中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      remove(this, { id: id }, function(r) {
          this.getTree();
          this.$message.success("删除成功");
        }.bind(this), function(f) {
          loading.close();
        }.bind(this)
      );
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.menuName,
        children: node.children
      };
    },
    commit() {
      let r = false;
      this.$refs["commitDialog"].validate(function(valid) {
        r = valid;
        return r;
      }.bind(this));
      if (!r) {
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "提交中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      if (this.dialog.params.id) {
        update(this, this.dialog.params, function(res) {
          this.getTree();
          this.dialog.visible = false;
        }.bind(this), function(f) {
          loading.close();
        }.bind(this));
      } else {
        add(this, this.dialog.params, function(res) {
          this.getTree();
          this.dialog.visible = false;
        }.bind(this), function(f) {
          loading.close();
        });
      }
    }
  }
};
</script>

<template>
  <div style="margin: 20px 0">
    <div class="header">
      <!-- 搜素栏目 -->
      <el-form :model="query" ref="queryForm" size="mini" :inline="true">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="query.menuName" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getTree">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="small" type="primary" @click="handleAdd()" v-permission="'menu.create'">新增</el-button>
      </div>
    </div>
    <div class="main">
      <el-table
        :data=tree
        row-key="id"
        :tree-props="{children: 'children'}"
        height="75vh"
      >
        <el-table-column
          label="菜单名称"
          align="left"
          prop="menuName"
          width="400">
        </el-table-column>

        <el-table-column
          label="图标"
          align="center"
          width="50"
        >
          <template
            slot-scope="{row}"
          >
            <em :class="row.menuIcon"></em>
          </template>
        </el-table-column>

        <el-table-column
          label="排序"
          align="center"
          prop="sort"
          width="50"
        >
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          label="权限标识"
          align="center"
          prop="permissions"
          width="300"
        >
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          label="组件访问路径"
          align="center"
          prop="requestUrl"
          width="300"
        >
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="{row}">
            <el-button style="color: #70a1ff;font-weight: bold" size="mini" type="text" icon="el-icon-edit"
                       @click="handleUpdate(row)" v-permission="'menu.update'">修改
            </el-button>
            <el-button style="color: #2ed573;font-weight: bold" size="mini" type="text" icon="el-icon-plus"
                       @click="handleAdd(row)" v-permission="'menu.create'">新增
            </el-button>
            <el-popconfirm
              style="margin-left: 10px"
              title="删除此内容吗？"
              @confirm="handleDelete(row.id)"
            >
              <el-button style="color: #ff4757;font-weight: bold" slot="reference" size="mini" type="text"
                         icon="el-icon-delete" v-permission="'menu.delete'">删除
              </el-button>
            </el-popconfirm>

          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog
      :close-on-click-modal=false
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="700px"
    >
      <el-alert
        style="margin-bottom: 10px;"
        title="菜单只支持父子两层渲染 (即:根->父菜单->子菜单) 权限则无此要求 "
        type="warning"
        effect="dark">
      </el-alert>
      <el-form :model="dialog.params" :rules="dialog.rules" ref="commitDialog" label-position="left" size="mini"
               label-suffix=" : ">
        <el-form-item label="上级菜单" prop="parentId" label-width="80px">
          <treeselect v-model="dialog.params.parentId" :options="menuTree" :normalizer="normalizer" :show-count="true"
                      placeholder="选择上级菜单" />
        </el-form-item>
        <el-form-item label="名称" prop="name" label-width="60px">
          <el-input
            v-model="dialog.params.name"
            placeholder="请输入名称"
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item label="类型" prop="flag" label-width="50px">
          <el-radio-group v-model="dialog.params.flag">
            <el-radio :label="1">菜单权限</el-radio>
            <el-radio :label="2">操作权限</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-show="dialog.params.flag === 1" label="访问路径"
                      prop="requestUrl" label-width="80px">
          <el-input
            v-model="dialog.params.requestUrl"
            placeholder="请输入访问路径 (根目录可不填)"
            maxlength="50"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item v-show="dialog.params.flag === 1" label="组件路径" prop="component"
                      label-width="80px">
          <el-input
            v-model="dialog.params.component"
            placeholder="请输入组件路径 (根目录可不填)"
            maxlength="50"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item v-show="dialog.params.flag === 1" label="图标代码" prop="menuIcon" label-width="80px">
          <el-input
            v-model="dialog.params.menuIcon"
            placeholder="请输入图标代码"
          >
          </el-input>
        </el-form-item>

        <el-form-item v-show="dialog.params.flag === 1" label="是否开启页面缓存" prop="keepAlive"
                      label-width="150px">
          <el-switch
            v-model="dialog.params.keepAlive"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>

        <el-form-item v-show="dialog.params.flag === 2" label="权限代码" prop="permissions" label-width="80px">
          <el-input
            v-model="dialog.params.permissions"
            placeholder="请输入权限代码"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="排序序号" prop="sort" label-width="80px">
          <el-input-number v-model="dialog.params.sort" :min=1 :max=1000>
          </el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="medium" type="info" @click="dialog.visible = false">取消</el-button>
        <el-button size="medium" type="primary" @click="commit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>

/deep/ .el-table th {
  background-color: #f1f2f6 !important;
}

.main {
  margin: 10px 0
}
</style>